/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/10/23
 **/
'use strict';
let path  =require('path');
let fs = require('fs');
let fse = require('fs-extra');

let util  = module.exports={};

let __workbenchName ="";
util.getWorbenchName  =function (){
  
  if(!__workbenchName){
    let name  =path.join(__dirname,'..');
    let _files  = name.split(path.sep);
    __workbenchName =_files[_files.length-1];
  }
  // console.log(name);
  
  return __workbenchName;
}
util.getWorbenchName();

util.generateTemplateConfigContent = function * ({templateConfig }) {
  
  let templateJs = '',templateCss ='';
  
  for(let i =0,ilen=templateConfig.dependenciesBar.length ; i<ilen; i++){
    let widgetNs  = templateConfig.dependenciesBar[i];
    let barDefaultPropsMap;
    if(templateConfig.barDefaultPropsMap){
      barDefaultPropsMap = templateConfig.barDefaultPropsMap[widgetNs];
    }
    let {js,css}  =  yield _loadWidgetJSFile(widgetNs,barDefaultPropsMap);
    templateJs+=js;
    templateCss+=css;
  }
  
  templateJs +=`;(function(){
     window.__XSite_template_register(${JSON.stringify(templateConfig)});
     xDllContext.iflux.msg.emit("__XSite_Template_Loaded_${templateConfig.templateName}", "${templateConfig.templateName}");
  })();`;
  return  {templateJs,templateCss};
}


function * _loadWidgetJSFile(widgetNs, widgetDefaultProps) {
  
  let widgetPath;
  if (widgetNs.startsWith(__workbenchName)) {
    widgetPath = path.join(__dirname, '../dist/barRepo', widgetNs);
    console.log('加载本项目文件到模板编译文件中');
  } else { //依赖外部的 bar
    //TODO
    console.log('加载外部项目文件到模板编译文件中');
    // let _filePath ="@qianmi/" + widgetNs;
    widgetPath = path.join(__dirname, '../node_modules/@qianmi', widgetNs);
    throw new Error('暂未 实现此功能!');
  }
  
  // fs.readFile();
  console.log('读取每个组件的js -p.js .css',widgetPath,'========================================================');
  
  
  let [widgetJs,widgetPJs] = yield [loadFile(widgetPath + ".js"), loadFile(widgetPath + "-p.js")];
  let widgetCss  ="";
  if(widgetPath === '/Users/dong/workbench/x-ui/x-site-ui-article/dist/barRepo/x-site-ui-article/pc/foot-bar/mi/mi-foot-top'){
    console.log('dingdong');
  }
  try{
    widgetCss  = yield loadFile(widgetPath + ".css");
  }catch(err){
    console.warn(widgetPath + ".css 加载失败, 可能本组件就不需要这个样式文件");
  }
  
  //包含组件的转换属性...
  if (widgetDefaultProps) {
    if (typeof widgetDefaultProps === 'function') {
      //把函数源代码赋值过去.
      widgetDefaultProps = widgetDefaultProps.toString();
    } else {
      widgetDefaultProps = JSON.stringify(widgetDefaultProps);
    }
    
    let _begIndex = widgetPJs.indexOf('__XSite_widgetInject');
    let _startIndex = widgetPJs.indexOf(',{', _begIndex);
    
    let _preContent = widgetPJs.substring(0, _startIndex);
    let _postContent = widgetPJs.substring(_startIndex);
    
    widgetPJs = _preContent + `widgetDefaultProps:${widgetDefaultProps},` + _postContent
  }
  
  return {js: widgetJs + widgetPJs, css: widgetCss};
  
}

function * loadFile(filePath){
  return new Promise((resolve,reject)=>{
    fs.readFile(filePath, (err, data) => {
      // if (err) throw err;
      err?reject(err):resolve(data.toString());
    });
  });
}